const App = getApp();
import {
	url
} from '../../../../modelApi/url_config.js'
Page({
	data: {
		linshifang: false,
		maskHidden: false,
		scrollTop: 0,
		id: "", //直播id
		statusBarPadding: "",
		inputModalVisible: false, // 显示聊天框
		pushUrl: "", //直播推流地址
		IMmsgList: [],
		nickName: wx.getStorageSync('nickName'),
		avatar: wx.getStorageSync('avatar'),
		ctx: null,
		numval: 3, // 倒计时
		hideflag: false, // 隐藏盒子，出现倒计时
		isHideBtn: true, // 倒计时完了隐藏盒子
		avatar: '',
		showShareBool: false,
		qrcodeImg: '',
		conmeinList: [],
		isshowCome: '',
		count: 0,
		imagePath: '',
		beauty: 0, //美颜，取值范围 0-9 ，0 表示关闭
		whiteness: 0, // 美白，取值范围 0-9 ，0 表示关闭
		showBeautiModel: false, //显示美颜弹窗
	},
	onLoad(options) {
		if (!App.globalData.isShow) {
			wx.redirectTo({
				url: "/pages/errorPage/index"
			});
			return
		}
		this.setData({
			linshifang: true
		})
		this.setData({
			statusBarPadding: App.globalData.navTop,
			id: options.id,
			avatar: wx.getStorageSync('avatar')

		});
		/* 获取直播间详情 */
		this.getQrcode()
	},
	onShow() {
		this.ImListen()
	},
	onReady() {
		this.getLiveInfo()
	},
	onHide() {
		App.globalData.wxTIM.off(App.globalData.TIM.EVENT.MESSAGE_RECEIVED, this.listenFucnback)
	},
	getQrcode() {
		const params = {
			page: 'pages/live/sonpages/player/player',
			scene: `${wx.getStorageSync('userId')}&${this.data.id}`,
			isHyaline: true,
			width: '280'
		}
		App.ajax(url.getQrcode, params, 'post').then(res => {
			this.setData({
				qrcodeImg: res.data
			})
		})
	},
	showshareDialog() {
		this.setData({
			showShareBool: true
		})
	},
	closeShareFunc() {
		this.setData({
			showShareBool: false
		})
	},
	ImListen() {
		App.globalData.wxTIM.on(App.globalData.TIM.EVENT.MESSAGE_RECEIVED, this.listenFucnback)
	},
	listenFucnback(res) {
		console.log(res, "？？？？？？？？？？？？消息通知11")
		this.setData({
			isshowCome: false
		})
		const list = [];
		const conmeinList = [];
		let isshowCome = false
		res.data.map(el => {
			if (el.from !== '@TIM#SYSTEM' && el.to === this.data.id && el.payload.text) {
				list.push(el)
			}
			if (el.payload.data &&  el.payload.data === 'comeinground' && el.to === this.data.id) {
				conmeinList.push(el)
				isshowCome= true
			}
		})
		this.setData({
			IMmsgList: [...this.data.IMmsgList, ...list],
			conmeinList: conmeinList,
			isshowCome: isshowCome
		})
		setTimeout(()=> {
			this.setData({
				isshowCome: false
			})
		},2000)
		this.goToBottom()
	},
	// 容器滚动到底部
	goToBottom() {
		const query = wx.createSelectorQuery().in(this);
		query.select('.messages-list').boundingClientRect();
		query.select('.msgList').boundingClientRect();
		query.exec(res => {
			const scorllHeight = res[0].height;
			const listHeight = res[1].height;
			this.setData({
				scrollTop: listHeight - scorllHeight
			});
		});
	},
	statechange(e) {
		console.log('live-pusher code:', e.detail.code)
	},
	cancelImgFunc() {
		this.setData({
			maskHidden: false
		})
	},
	saveImgFunc() {
		wx.saveImageToPhotosAlbum({
			filePath: this.data.imagePath,
			success(res) { }
		})
	},
	creatBanner() {
		var that = this;
		this.setData({
			maskHidden: false,
			showShareBool: false
		});
		wx.showToast({
			title: '图片生成中...',
			icon: 'loading',
			duration: 1000
		});
		setTimeout(function () {
			wx.hideToast()
			that.createNewImg();
			that.setData({
				maskHidden: true
			});
		}, 1000)
	},
	getTempFilePath: function () {
		wx.canvasToTempFilePath({
			canvasId: 'mycanvas',
			success: (res) => {
				this.setData({
					shareTempFilePath: res.tempFilePath
				})
			}
		})
	},
	downfile(url){//下载网络图片的promise对象
		return new Promise(function (resolve, reject) {
			wx.downloadFile({
				url:url ,
				success: function (res) {
					resolve(res.tempFilePath)
				}
			})
		})
	},
	createNewImg: function () {
		var that = this;
		var context = wx.createCanvasContext('mycanvas');
		// 背景
		context.setFillStyle("#fff")
		context.fillRect(0, 0, 500, 650)
		// 主图海报
		var path = wx.getStorageSync('shareImgZHUBO');
		context.drawImage(path, 20, 100, 360, 360);
		// 绘制名字
		context.setFontSize(20);
		context.setFillStyle('#333333');
		context.fillText(wx.getStorageSync('nickName'), 85, 60);
		context.stroke();
		// 绘制名字
		context.setFontSize(16);
		context.setFillStyle('#999999');
		context.setTextAlign('center');
		context.fillText('轮到你播', 60, 630);
		context.stroke();
		// 小程序码
		wx.downloadFile({
			url: that.data.qrcodeImg,
			success(qrcodeImgOBJ) {
				// 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
				if (qrcodeImgOBJ.statusCode === 200) {
					context.save()
					context.drawImage(qrcodeImgOBJ.tempFilePath, 252, 500, 128, 128);
					context.draw(true, () => {
						wx.canvasToTempFilePath({
							canvasId: 'mycanvas',
							success: function(res){
							},
						})
					});
				}
			}
		})
		// 头像
		wx.downloadFile({
			url: this.data.avatar,
			success(res) {
				// 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
				if (res.statusCode === 200) {
					context.save()
					context.beginPath()
					context.arc(50, 50, 30, 0, 2 * Math.PI)
					context.clip();
					context.drawImage(res.tempFilePath, 20, 20, 60, 60);
					context.restore()
					context.draw(true,() => {
						wx.canvasToTempFilePath({
							canvasId: 'mycanvas',
							success: function(res){
							},
						})
					});
				}
			}
		})
		context.draw();
		//将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
		setTimeout(function () {
			wx.canvasToTempFilePath({
				canvasId: 'mycanvas',
				success: function (res) {
					var tempFilePath = res.tempFilePath;
					that.setData({
						imagePath: tempFilePath,
						canvasHidden: true
					});
				},
				fail: function (res) {
					console.log(res);
				}
			});
		},3000);
	},
	bindStartFunc() {
		this.setData({
			hideflag: true
		})
		setTimeout(()=>{
			this.data.numval--;
			this.setData({
				numval:this.data.numval
			})
			if (this.data.numval>0) {
				this.bindStartFunc();
			}
			if (this.data.numval === 0) {
				this.setData({
					isHideBtn: false
				})
				this.startBofan()
			}
		},1000)
	},
	startBofan() {
		//调用推流摄像头
		this.data.ctx = wx.createLivePusherContext('pusher')
		this.setData({
			ctx: this.data.ctx
		})
		this.data.ctx.start({
			success: res => {},
			fail: res => {}
		})
	},
	xclose() {
		this.data.ctx && this.data.ctx.stop({
			success: res => {
				let params = {
					roomId: this.data.id
				}
				App.ajax(url.roomStopUrl, params, 'post').then(res => {
					/* 退出页面 */
					1 === getCurrentPages().length ? wx.switchTab({
						url: "/pages/mine/index"
					}) : wx.navigateBack();
				})
			},
			fail: res => {
				console.log('stop fail')
			}
		})
	},
	bindSwitchCamera() {
		this.data.ctx.switchCamera({
			success: res => {},
			fail: res => {}
		})
	},
	/* 获取直播间详情 */
	getLiveInfo() {
		let params = {
			roomId: this.data.id
			// skuId: e.target.dataset.skuid
		}
		wx.showLoading({
			title: "加载中..."
		});
		App.ajax(url.liveDetailUrl, params, 'get').then(res => {
			wx.hideLoading();
			this.setData({
				pushUrl: res.data.streamInfo.pushUrl
			})
		})
	},
	/* 退出 */
	onUnload() {
		this.xclose(); //结束推流
	},
	onShareAppMessage(res) {
		const url_data = `pages/live/sonpages/player/player?shareUserId=${wx.getStorageSync('userId')}&id=${this.data.id}`;
		return {
			title: wx.getStorageSync('nickName') + '的直播间',
			path: url_data,
			imageUrl: wx.getStorageSync('shareImgZHUBO')
		}
	},
	/* 弹出美颜 */
	beautiFun() {
		this.setData({
			showBeautiModel: !this.data.showBeautiModel
		})
	},
	/* 美颜 */
	beautiChange(e) {
		this.setData({
			beauty: e.detail.value
		})
	},
	/* 美白 */
	whitenessChange(e) {
		this.setData({
			whiteness: e.detail.value
		})
	}
})